#include "LFileOperateCommon.h"

int getFileLen(const wchar_t * file_name)
{
	FILE* file = _wfopen(file_name,L"rb");
	int pos = ftell(file);
	fseek(file,0,SEEK_END);
	int len = ftell(file) - pos;
	fclose(file);
	return len;
}

int getFileBuffer(const wchar_t * file_name, char** ucs16Buff)
{
	int length = 0;
	FILE* file = _wfopen(file_name, L"rb");
	if(file != NULL)
	{

		fseek( file, 0, SEEK_END );
		length = ftell( file );
		fseek( file ,0, SEEK_SET );
		*ucs16Buff = new char[length] ;
		memset( *ucs16Buff , 0 , length);


		if ( fread( *ucs16Buff,  1, length, file ) != length ) 
		{
			delete [] *ucs16Buff;
			*ucs16Buff = NULL;
			return length;

		}

	}
	fclose(file);
	return length;
}

std::wstring getFileName(const wchar_t* fullName)
{
	if(fullName == NULL)
		return L"";
	int idx = (int)wcslen(fullName);
	for(; idx >= 0 ; idx --)
	{
		if(fullName[idx] == '\\' || fullName[idx]=='/')
		{
			break;
		}
	}
	std::wstring _ret = fullName + (idx + 1);   
	return _ret;
}

std::wstring getPathName(const wchar_t* fullName)
{
	if(fullName == NULL)
		return L"";
	std::wstring _ret = fullName;   
	std::wstring::size_type pos = _ret.rfind('\\');
	if(pos == std::wstring::npos) 
	{
		pos = _ret.rfind('/');
	}
	if(pos == std::wstring::npos )
	{
		return L"";
	}

	_ret.replace(pos ,wcslen(fullName), L"");
	return _ret + PATH_SPLITTER_STRING;
}


bool _write_data_to_file(const char* pData, const wchar_t* file_name, int nLength )
{
	FILE* file = _wfopen(file_name , L"wb");
	if(file == NULL)
	{
		return false;
	}
	else
	{
		fwrite(pData, sizeof(char), nLength, file );
	}
	fclose(file);
	return true;
}

void create_all_dir(const wchar_t* bas_dir,const wchar_t* file)
{
	wchar_t dir_name[128];
	for(int i = 0 ; i < (int) wcslen(file) ; ++i)
	{
		if(file[i] == '/' || file[i] == '\\')
		{
			wcsncpy(dir_name,file,128);
			dir_name[i] = 0;
			std::wstring dir_full_name = std::wstring(bas_dir) + dir_name;

#ifdef _WIN32
			_wmkdir(dir_full_name.c_str());
#else

			//mkdir(mbsDirName,0777);
#endif

		}
	}
}